package com.shapawan.tourism.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shapawan.tourism.entity.AdminUser;
import com.shapawan.tourism.mapper.AdminUserMapper;
import com.shapawan.tourism.service.AdminUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 管理员用户服务实现类
 */
@Service
@Slf4j
public class AdminUserServiceImpl extends ServiceImpl<AdminUserMapper, AdminUser> implements AdminUserService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public AdminUser getByUsername(String username) {
        LambdaQueryWrapper<AdminUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AdminUser::getUsername, username);
        
        List<AdminUser> userList = list(queryWrapper);
        if (userList != null && !userList.isEmpty()) {
            // 如果找到多个用户，取第一个
            if (userList.size() > 1) {
                log.warn("找到多个用户名为 {} 的用户，返回第一个", username);
            }
            return userList.get(0);
        }
        
        return null;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("加载用户信息: {}", username);
        AdminUser user = getByUsername(username);
        if (user == null) {
            log.error("用户不存在: {}", username);
            throw new UsernameNotFoundException("用户不存在: " + username);
        }
        log.info("找到用户: {}, 角色: {}, 状态: {}", username, user.getRole(), user.getStatus());
        return user;
    }

    @Override
    public boolean updatePassword(Integer userId, String oldPassword, String newPassword) {
        AdminUser user = getById(userId);
        if (user == null) {
            return false;
        }
        
        // 验证旧密码
        if (!passwordEncoder.matches(oldPassword, user.getPassword())) {
            return false;
        }
        
        // 更新密码
        user.setPassword(passwordEncoder.encode(newPassword));
        return updateById(user);
    }
} 